/**
 * Alipay.com Inc. Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.yeyks.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yeyks.base.Arguments;
import com.yeyks.exception.ServiceException;
import com.yeyks.exception.SmsSendException;
import com.yeyks.model.enums.SmsTypeEnum;
import com.yeyks.service.SmsHistoryService;
import com.yeyks.service.SmsService;
import com.yeyks.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author Beacon
 * @version $Id: SmsServiceImpl.java, v 0.1 2018年08月13日 16:04 Beacon Exp $
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsHistoryService smsHistoryService;

    // TODO:恢复mock，设置为 null
    public static Integer mockCode = null;

    class PhoneSmsInfo {
        public long lastCodeTimestamp;      // 上一次发送验证码的时间戳
        public String lastSmsCode;          // 上一次验证码的内容

    }

    /**
     * 获得四位随机验证码
     *
     * @return
     */
    public static String getRandom() {
        String str = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            sb.append(str.charAt(random.nextInt(str.length())));
        }
        return sb.toString();
    }

    //短信API产品名称
    static final String product = "Dysmsapi";
    //短信API产品域名
    static final String domain = "dysmsapi.aliyuncs.com";

    static final String accessKeyId = "LTAITpv2oyvCJueR";
    static final String accessKeySecret = "FC20WVDv4nHzQ77TQaZBzkgCsBYJB4";

    static Map<String, PhoneSmsInfo> smsCodeMap = new HashMap<>();

    public SendSmsResponse sendSms(String phone, String signName, String templateCode, String templateParam) throws Exception {

        //设置超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //待发送的手机号
        request.setPhoneNumbers(phone);
        //短信签名
        request.setSignName(signName);
        //短信模板ID
        request.setTemplateCode(templateCode);
        /*
         * 可选:模板中的变量替换JSON串,
         * 如模板内容为"亲爱的${name},您的验证码为${code}"时,
         * 此处的值为{"name":"Tom","code":"1454"}
         *   \  反斜杠为转义字符，使得输出双引号
         */
        request.setTemplateParam(templateParam);
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("1454");
        SendSmsResponse response = null;
        if (mockCode != null) {
            response = new SendSmsResponse();
            response.setCode("OK");
        } else {
            response = acsClient.getAcsResponse(request);
        }

        return response;
    }

    private JSONObject sendSmsV2(String phone, String signName, String templateCode, String templateParam) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);
        JSONObject jsonObject = null;
        try {
            CommonResponse response = client.getCommonResponse(request);
            if (response != null && response.getData() != null) {
                jsonObject = JSONObject.parseObject(response.getData());
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

//    @Override
//    public void sendSmsForSignup(String phone) throws Exception {
//
//        PhoneSmsInfo smsInfo = smsCodeMap.get(phone);
//        if (smsInfo != null) {
//            long timeElapse = System.currentTimeMillis() - smsInfo.lastCodeTimestamp;
//            if (timeElapse < 60 * 1000) {
//                SmsSendException exception = new SmsSendException();
//                exception.setWait(60 * 1000 - timeElapse);
//                throw exception;
//            }
//        }
//
//        //验证码
//        String code = getRandom();
//        SendSmsResponse response = sendSms(phone, "夜鱼", "SMS_147725180", "{\"code\":\"" + code + "\"}");
//        if (response != null && response.getCode() != null && response.getCode().equals("isv.BUSINESS_LIMIT_CONTROL")) {
//            log.info(response.getMessage());
//            throw new ServiceException("同一个手机号发送过于频繁");
//        }
//        if (response != null && response.getCode() != null && response.getCode().equals("OK")) {
//            smsHistoryService.insertByPhoneDesc(phone, SmsTypeEnum.REGIST.desc(), code);
//            // 请求成功
//            smsInfo = new PhoneSmsInfo();
//            smsInfo.lastCodeTimestamp = System.currentTimeMillis();
//            smsInfo.lastSmsCode = (mockCode != null ? mockCode.toString() : code);
//            smsCodeMap.put(phone, smsInfo);
//        } else {
//            // 请求失败
//            throw new SmsSendException();
//        }
//    }

    @Override
    public void sendSmsForSignup(String phone) throws Exception {

        PhoneSmsInfo smsInfo = smsCodeMap.get(phone);
        if (smsInfo != null) {
            long timeElapse = System.currentTimeMillis() - smsInfo.lastCodeTimestamp;
            if (timeElapse < 60 * 1000) {
                SmsSendException exception = new SmsSendException();
                exception.setWait(60 * 1000 - timeElapse);
                throw exception;
            }
        }
        //验证码
        String code = getRandom();
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        JSONObject jsonObject = sendSmsV2(phone, "夜鱼", "SMS_147725180", JSONObject.toJSONString(map));
        if (jsonObject != null && jsonObject.get("Code").equals("OK")) {
            smsHistoryService.insertByPhoneDesc(phone, SmsTypeEnum.REGIST.desc(), code);
            // 请求成功
            smsInfo = new PhoneSmsInfo();
            smsInfo.lastCodeTimestamp = System.currentTimeMillis();
            smsInfo.lastSmsCode = (mockCode != null ? mockCode.toString() : code);
            smsCodeMap.put(phone, smsInfo);
        } else {
            // 请求失败
            throw new SmsSendException();
        }
    }

    /**
     * 给酒店发送下单成功提示短信
     *
     * @param phone
     * @throws Exception
     */
    @Override
    public void sendSmsForOrderComplete(String phone) throws Exception {
        sendSms(phone, "夜鱼", "SMS_142151771", "{}");
        smsHistoryService.insertByPhoneDesc(phone, SmsTypeEnum.ORDER.desc(), "SMS_142151771");
    }

    @Override
    public boolean verifySmsForSignup(String phone, String code) {

        try {
            String sucCode = smsCodeMap.get(phone).lastSmsCode;
            return sucCode.compareToIgnoreCase(code) == 0;
        } catch (Throwable e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 给用户发送短信返回密码
     *
     * @param phone
     * @param password
     * @return
     */
//    @Override
//    public boolean sendPwcSms(String phone, String password) {
//        try {
//            SendSmsResponse response = sendSms(phone, "夜鱼", "SMS_160575459", "{\"code\":\"" + password + "\"}");
//            if (response != null) {
//                if (response.getCode() != null && response.getCode().equals("OK")) {
//                    smsHistoryService.insertByPhoneDesc(phone, SmsTypeEnum.REMINDPWD.desc(), password);
//                    // 请求成功
//                    return true;
//                } else {
//                    log.info(response.toString());
//                    return false;
//                }
//            } else {
//                return false;
//            }
//        } catch (Exception e) {
//            // 请求失败
//            log.info("发送短信服务器异常{}", e.getLocalizedMessage());
//            return false;
//        }
//    }

    @Override
    public boolean sendPwcSms(String phone, String password) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", password);
        return sendSmsToBoolean(map, "SMS_160575459");
    }

    /**
     * 给用户发送下单成功提示短信
     *
     * @param phone     手机号
     * @param person    下单用户名
     * @param daytime   入住时间
     * @param hotelname 酒店名称
     * @param roomtype  房间类型
     * @param roomnum   预定多少间房间
     * @param roomnight 入住几晚
     * @param address   酒店地址
     * @param hoteltel  酒店联系电话
     * @return
     */
    @Override
    public Boolean sendSmsToUserForOrderComplete(String phone, String person, String daytime, String hotelname, String roomtype, String roomnum, String roomnight, String address, String hoteltel) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("person", person);
        map.put("daytime", daytime);
        map.put("hotel", hotelname + roomtype + roomnum + "间" + roomnight + "晚");
        map.put("address", address);
        map.put("hoteltel", hoteltel);
        smsHistoryService.insertByPhoneDesc(phone, SmsTypeEnum.ORDER.desc(), JSONObject.toJSONString(map));
        return sendSmsToBoolean(map, "SMS_162520410");
    }

    /**
     * 用户发送退款申请发送短信通知酒店
     *
     * @param phone     手机号
     * @param person    下单用户名
     * @param daytime   入住时间
     * @param hotelname 酒店名称
     * @param roomtype  房间类型
     */
    @Override
    public Boolean sendSmsForUserRefund(String phone, String person, String daytime, String hotelname, String roomtype) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("person", person);
        map.put("daytime", daytime);
        map.put("hotel", hotelname + roomtype );
        smsHistoryService.insertByPhoneDesc(phone, SmsTypeEnum.USERREFUNDORDER.desc(), JSONObject.toJSONString(map));
        return sendSmsToBoolean(map, "SMS_162520416");
    }

    /**
     * 当酒店无法接单时退款，给用户发送短信通知
     *
     * @param phone     手机号
     * @param daytime   入住时间
     * @param hotelname 酒店名称
     * @param roomtype  房间类型
     * @return
     */
    @Override
    public Boolean sendSmsForHotelRefund(String phone, String daytime, String hotelname, String roomtype) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("daytime", daytime);
        map.put("hotel", hotelname + roomtype);
//        map.put("hotelname", hotelname);
//        map.put("roomtype", roomtype);
        smsHistoryService.insertByPhoneDesc(phone, SmsTypeEnum.HOTELREFUNDORDER.desc(), JSONObject.toJSONString(map));
        return sendSmsToBoolean(map, "SMS_162520427");
    }

    /**
     * 用户下单成功酒店通知短信
     *
     * @param phone     手机号
     * @param person    下单用户名
     * @param daytime   入住时间
     * @param hotelname 酒店名称
     * @param roomtype  房间类型
     * @param roomnum   预定多少间房间
     * @param roomnight 入住几晚
     * @return
     */
    @Override
    public Boolean sendSmsToHotelForOrderComplete(String phone, String person, String daytime, String hotelname, String roomtype, String roomnum, String roomnight) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("person", person);
        map.put("daytime", daytime);
        StringBuilder sb = new StringBuilder();
        if (Arguments.notEmpty(hotelname)) {
            sb.append(hotelname);
        }
        if (Arguments.notEmpty(roomtype)) {
            sb.append(roomtype);
        }
        if (Arguments.notEmpty(roomnum)) {
            sb.append(roomnum).append("间");
        }
        if (Arguments.notEmpty(roomnight)) {
            sb.append(roomnight).append("晚");
        }
        map.put("hotel", sb.toString());
        smsHistoryService.insertByPhoneDesc(phone, SmsTypeEnum.ORDER.desc(), JSONObject.toJSONString(map));
        return sendSmsToBoolean(map, "SMS_162520430");
    }

    private Boolean sendSmsToBoolean(Map<String, String> map, String templateCode) {
        try {
            String phone = map.get("phone");
            JSONObject jsonObject = sendSmsV2(phone, "夜鱼", templateCode, JSONObject.toJSONString(map));
            if (jsonObject != null && jsonObject.get("Code").equals("OK")) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.info("发送短信服务器异常{}", e.getLocalizedMessage());
            return false;
        }
    }
}